<template>
  <a-form :labelCol="{ span: 4 }" :model="formState" :rules="rules" @finish="onFinish">
    <a-form-item label="邮箱" name="email">
      <a-input placeholder="请输入邮箱" v-model:value="formState.email" />
    </a-form-item>
    <a-form-item label="密码" name="password">
      <a-input-password placeholder="请输入密码" v-model:value="formState.password" />
    </a-form-item>
    <a-form-item>
      <a-button class="w-full" type="primary" htmlType="submit">
        登录
      </a-button>
    </a-form-item>
  </a-form>
</template>

<script setup>
import { reactive } from 'vue';
import { useUserStore } from '../../../../stores/user'
import { message } from 'ant-design-vue';
import { login } from '../../../../docsapi/user'
const userStore = useUserStore()
const formState = reactive({
  email: '',
  password: '',
})
const rules = {
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'change' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'change' },
    { min: 6, max: 20, message: '密码长度必须在6到20个字符之间', trigger: 'change' }
  ],
}

const onFinish = (values) => {
  console.log('登录信息:', values);
  login(values).then(response => {
    if (response.code !== 0) {
      message.error(response.error || '登录失败');
      return
    }
    // 保存token到本地
    // 获取用户信息
    localStorage.setItem('token', response.data.token);
    userStore.setToken(response.data.token);
    message.success('登录成功');
    // 跳转到首页
    // window.location.href = '/';
  })
}

</script>
